package com.CGFrame.struts.bean.material;

import java.io.File;
import java.util.LinkedList;

import com.CGFrame.struts.POJOs.Material;
import com.CGFrame.struts.POJOs.Materialgroup;
import com.CGFrame.struts.bean.ProjectOperate;
import com.CGFrame.struts.bean.ProjectOperateFactory;
import com.config.GenericConfig;

public class MaterialgroupBean {
	private Materialgroup materialGroup;
	
	private static String materialBase = GenericConfig.getInstance().getMaterial();	

	
	public MaterialgroupBean(int materialGroupId)
	{
		ProjectOperate pop = ProjectOperateFactory.getprojectOperate();
		materialGroup = (Materialgroup)pop.UniqueQuery("Materialgroup", "materialGroupId,"+materialGroupId);		
	}
	public MaterialgroupBean(Materialgroup mg ,String name)
	{
		ProjectOperate pop = ProjectOperateFactory.getprojectOperate();
		materialGroup = new Materialgroup(mg,name,null,null);
		pop.saveObject(materialGroup);
		mk();
	}
	public Materialgroup getMaterialgroup()
	{
		return materialGroup;
	}
	
	private void mk()
	{
		StringBuffer path = new StringBuffer(materialBase);
		LinkedList<String> list =  this.getMaterialGroupNameList();
		while ( !(list.isEmpty()) )
		{
			path.append("/").append(list.poll());
		}
		path.append("/").append(materialGroup.getMaterialGroupName());
		mkdictory(path.toString());
	}
			
	public LinkedList<String> getMaterialGroupNameList()
	{
		LinkedList<String> list = new LinkedList<String>();
		Materialgroup mg = materialGroup.getMaterialgroup();
		while(mg!=null)
		{
			list.addFirst(mg.getMaterialGroupName());
			mg = mg.getMaterialgroup();
		}
		return list;
	}

	public String getName() {
		return materialGroup.getMaterialGroupName();
	}
	private void mkdictory(String fileName) {
		File file = new File(fileName);
		if (!file.exists()) {
			file.mkdirs();
		}
	}
	private boolean isRoot()
	{
		return (materialGroup.getMaterialgroup()==null);
	}
	public String delete()
	{
		if (isRoot()) return null;
		String name = materialGroup.getMaterialGroupName();
		ProjectOperate pop = ProjectOperateFactory.getprojectOperate();
		pop.delete(materialGroup);
		return name;
	}
	
}
